package orz.mikeneck.server.locrec;

import java.io.IOException;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.UserServiceFactory;

import orz.mikeneck.server.locrec.model.LocRecUserModel;
import orz.mikeneck.server.locrec.model.LocRecUserModelImpl;
import orz.mikeneck.server.locrec.persistent.LocRecUser;
import orz.mikeneck.server.locrec.persistent.utils.PersistenceManagerUtil;
import orz.mikeneck.server.locrec.utils.UserServiceUtil;

public class LocRecUserServlet extends HttpServlet {

	private static final long serialVersionUID = 4953347885043189876L;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		UserServiceUtil util = new UserServiceUtil(
				UserServiceFactory.getUserService());
		String loginId;
		try{
			loginId = req.getParameter("loginId");
		}catch(NumberFormatException e){
			return;
		}
		String email = util.getEmail();
		PersistenceManager manager = PersistenceManagerUtil.getManager();
		
		LocRecUserModel model = new LocRecUserModelImpl()
			.emailIs(email)
			.persistenceManagerIs(manager)
			.createCountQuery();
		try {
			if(!model.isUserExisting()){
				LocRecUser user = new LocRecUser(loginId, email);
				manager.makePersistent(user);
			}
		} finally {
			manager.close();
		}
		resp.sendRedirect("/location/index.jsp");
	}

}
